<template>
  <div>
    <!-- 头部导航 -->
    <Breadcrumb menu="商品管理" submenu="商品分类" />

    <el-card>
      <el-button type="primary" @click="showAddCateDilog">添加分类</el-button>
      <!-- table表格数据 -->
      <vxe-table
        :data="cateList"
        border
        round
        :row-config="{ isHover: true }"
        size="medium"
        :tree-config="{ rowField: 'cat_id', parentField: 'cat_pid' }"
      >
        <vxe-column field="cat_id" title="id" width="100"></vxe-column>
        <vxe-column title="分类名称" tree-node>
          <template #default="{ row }">
            <span v-if="!row._edit">{{ row.cat_name }}</span>
            <el-input
              v-else
              v-model.trim="row._cat_name"
              @keyup.enter.native="saveEditData(row)"
              @blur="cancelEdit(row)"
              ref="editCatInputRef"
            ></el-input>
          </template>
        </vxe-column>
        <vxe-column title="是否有效">
          <template #default="{ row }">
            <i
              v-if="!row.cat_deleted"
              class="el-icon-success"
              style="color: lightgreen; font-size: 20px"
            ></i>
            <i
              v-else
              class="el-icon-error"
              style="color: red; font-size: 20px"
            ></i>
          </template>
        </vxe-column>
        <vxe-column title="排序">
          <template #default="{ row }">
            <el-tag size="mini" v-if="row.cat_level === 0">一级</el-tag>
            <el-tag size="mini" v-else-if="row.cat_level === 1" type="success"
              >二级</el-tag
            >
            <el-tag size="mini" v-else type="warning">三级</el-tag>
          </template>
        </vxe-column>
        <vxe-column title="操作" #default="{ row }">
          <!-- 取消编辑 -->
          <!-- <EditButton
            v-if="row._edit"
            style="margin-right:10px"
            @cancel="cancelEdit(row)"
            @complete="saveEditData(row)"
          /> -->
          <!-- 编辑按钮 -->
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            round
            @click="editCatData(row)"
            >编辑</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            round
            @click="deleteCateById(row)"
            >删除</el-button
          >
        </vxe-column>
      </vxe-table>

      <!-- 底部分页栏目 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      @close="addCateDialogClose"
      width="30%"
    >
      <!-- 添加分类表单 -->
      <el-form
        ref="addCateFormRef"
        :rules="addCateFormRules"
        :model="addCateForm"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cate_name">
          <el-input v-model.trim="addCateForm.cate_name"></el-input>
        </el-form-item>
        <el-form-item label="父类名称:">
          <el-cascader
            v-model="addCateForm.selectKeys"
            clearable
            :options="parentCateList"
            :props="cascaderProps"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      // 商品分类列表数据
      cateList: [],
      //查询商品分类列表数据对象
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品列表总条数
      total: 0,
      //控制添加分类对话框的显示和隐藏
      addCateDialogVisible: false,
      // 添加分类表单数据
      addCateForm: {
        cate_name: "",
        //选中的id
        selectKeys: [],
      },
      //添加分类表单校验
      addCateFormRules: {
        cate_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //父级分类列表
      parentCateList: [],
      // 指定级联选择的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true,
      },
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      res.data.result.recursive("children", (el) => {
        el._edit = false;
        el._cat_name = el.cat_name;
      });
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    //取消编辑
    cancelEdit(cate) {
      cate._edit = false;
      cate._cat_name = cate.cat_name;
    },
    //获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      this.parentCateList = res.data;
    },
    //显示添加分类对话框
    showAddCateDilog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    addCateDialogClose() {
      this.$refs.addCateFormRef.resetFields();
      this.addCateForm.selectKeys = [];
    },
    editCatData(row) {
      row._edit = true;
      this.$nextTick((_) => {
        this.$refs.editCatInputRef.focus();
      });
    },
    //添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (val) => {
        if (!val) return;
        var cat_pid =
          this.addCateForm.selectKeys.length === 0
            ? 0
            : this.addCateForm.selectKeys.last();
        await this.$http.post("categories", {
          cat_pid: cat_pid,
          cat_name: this.addCateForm.cate_name,
          cat_level: this.addCateForm.selectKeys.length,
        });
        this.$message.success(`添加分类 ${this.addCateForm.cate_name} 成功`);
        this.addCateDialogVisible = false;
        this.getCateList();
      });
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getCateList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getCateList();
    },
    //保存并提交编辑过后的数据
    async saveEditData(cate) {
      await this.$http.put(
        `categories/${cate.cat_id}`,
        {
          cat_name: cate._cat_name,
        },
        {
          rejectCall: () => {
            cate._edit = false;
          },
        }
      );
      cate.cat_name = cate._cat_name;
      cate._edit = false;
      this.$message.success("信息修改成功");
    },
    //根据id删除分类
    deleteCateById(cate) {
      this.$confirm(
        `此操作将永久删除分类 ${cate.cat_name}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${cate.cat_id}`
          );
          this.$message.success(`删除分类 ${cate.cat_name} 成功!`);
          this.getCateList();
        })
        .catch((error) => error);
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.vxe-table {
  margin: 15px 0;
}
.el-card .vxe-table /deep/ input {
  height: 25px;
}
.el-cascader {
  width: 100%;
}
</style>